package de.doegel.common;

import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;
import greendroid.widget.QuickAction;
import greendroid.widget.QuickActionBar;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;

import java.sql.SQLException;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import de.doegel.common.model.AbstractMessage;
import de.doegel.common.model.IncomingMessage;
import de.doegel.common.model.OutgoingMessage;
import de.doegel.common.ormlite.OrmLiteGDActivity;
import de.doegel.common.util.Utils;

public class MessageDetailsActivity<H extends AbstractDatabaseHelper> extends OrmLiteGDActivity<H> {
	private static class CustomQuickAction extends QuickAction {
		private static final ColorFilter BLACK_CF = new LightingColorFilter(Color.BLACK, Color.BLACK);

		public CustomQuickAction(Context ctx, int drawableId, int titleId) {
			super(ctx, buildDrawable(ctx, drawableId), titleId);
		}

		private static Drawable buildDrawable(Context ctx, int drawableId) {
			Drawable d = ctx.getResources().getDrawable(drawableId);
			d.setColorFilter(BLACK_CF);
			return d;
		}

	}

	private AbstractMessage message = null;
	private boolean inbox;

	private QuickActionBar quickActionBar;
	
	private boolean unreadMessage = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setActionBarContentView(R.layout.message_details);
		setTitle(R.string.message_details_activity_title);

		addActionBarItem(Type.Trashcan, R.id.action_bar_delete);
		addActionBarItem(Type.Compose, R.id.action_bar_compose);

		quickActionBar = new QuickActionBar(this);
		quickActionBar.addQuickAction(new CustomQuickAction(this, R.drawable.gd_action_bar_compose, R.string.message_compose));
		quickActionBar.addQuickAction(new CustomQuickAction(this, R.drawable.gd_action_bar_export, R.string.message_reply));
		quickActionBar.addQuickAction(new CustomQuickAction(this, R.drawable.gd_action_bar_share, R.string.message_forward));
		quickActionBar.setOnQuickActionClickListener(new OnQuickActionClickListener() {
			public void onQuickActionClicked(QuickActionWidget widget, int position) {
				switch (position) {
				case 0:
					composeMessage();
					break;
				case 1:
					replyMessage();
					break;
				case 2:
					forwardMessage();
					break;
				default:
					break;
				}
			}
		});

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			inbox = extras.getBoolean(IDoegelConstants.IS_INBOX_EXTRA);
			int messageId = extras.getInt(IDoegelConstants.MESSAGE_ID_EXTRA);
			try {
				if (inbox) {
					message = getHelper().getInboxDao().queryForId(messageId);
				} else {
					message = getHelper().getOutboxDao().queryForId(messageId);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		((TextView)findViewById(R.id.message_tofrom)).setText(inbox ? R.string.message_sender : R.string.message_receiver);

		Button contactNameButton = (Button) findViewById(R.id.contact_name);
		contactNameButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (message != null) {
					startActivity(Utils.createPersonIntent(MessageDetailsActivity.this, message.fromtoId, message.fromtoName));
				}
			}
		});
		TextView subjectdateText = (TextView) findViewById(R.id.message_subject_date);
		TextView contentText = (TextView) findViewById(R.id.message_content);

		contactNameButton.setText(message == null ? "Error" : message.fromtoName);
		subjectdateText.setText(message == null ? "Error" : (message.subject + "\n" + Utils.parseAndFormatDate(message.date, IDoegelConstants.MESSAGE_DATE_PARSER_FORMAT, IDoegelConstants.MESSAGE_DETAILS_DATE_FORMATTER_FORMAT)));
		contentText.setText(message == null ? "Error" : message.content);
		
		if (message != null && message instanceof IncomingMessage && !message.read) {
			new SetMessageReadTask().execute();
		}
	}

	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		if (item.getItemId() == R.id.action_bar_delete) {
			deleteMessage();
			return true;
		} else if (item.getItemId() == R.id.action_bar_compose) {
			quickActionBar.show(item.getItemView());
			return true;
		} else {
			return super.onHandleActionBarItemClick(item, position);
		}
	}
	
	public void deleteMessage() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.message_remove_are_you_sure)).setCancelable(true).setPositiveButton(getString(R.string.dialog_yes), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				if (message != null) {
					new DeleteMessageTask().execute(message);
				}
			}
		}).setNegativeButton(getString(R.string.dialog_no), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.setTitle(R.string.dialog_warning);
		builder.create().show();
	}

	public void composeMessage() {
		if (message != null) {
			startActivity(Utils.createComposeMessageIntent(this, message.fromtoId, message.fromtoName, null, null));
		}
	}

	public void replyMessage() {
		if (message != null) {
			startActivity(Utils.createComposeMessageIntent(this, message.fromtoId, message.fromtoName, getString(R.string.message_reply_subject) + " " + message.subject, "\n" + getString(R.string.message_reply_content) + "\n" + message.content));
		}
	}

	public void forwardMessage() {
		if (message != null) {
			startActivity(Utils.createComposeMessageIntent(this, -1, null, getString(R.string.message_forward_subject) + " " + message.subject, "\n" + getString(R.string.message_forward_content) + "\n" + message.content));
		}
	}
	
	public void onBackPressed () {
		if (message != null && unreadMessage) {
			Intent intent = new Intent();
	    	intent.putExtra(IDoegelConstants.MESSAGE_ID_EXTRA, message.id);
	    	if (MessageDetailsActivity.this.getParent() == null) {
				MessageDetailsActivity.this.setResult(IDoegelConstants.MESSAGE_READ_RESULT, intent);
			} else {
				MessageDetailsActivity.this.getParent().setResult(IDoegelConstants.MESSAGE_READ_RESULT, intent);
			}
		}
		super.onBackPressed();
	}
	
	
	private class DeleteMessageTask extends AsyncTask<AbstractMessage, Void, Boolean> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(MessageDetailsActivity.this);
			dialog.setMessage(getString(R.string.message_removing));
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();
		}

		@Override
		protected Boolean doInBackground(AbstractMessage... params) {
			AbstractMessage message = params[0];
			return ((DoegelApplication) getApplication()).getHttpConnector().deleteMessage(MessageDetailsActivity.this, message.id);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				int messageId = message.id;
				try {
					if (message instanceof IncomingMessage) {
						getHelper().getInboxDao().delete((IncomingMessage)message);
					} else {
						getHelper().getOutboxDao().delete((OutgoingMessage)message);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				dialog.dismiss();
				Intent intent = new Intent();
				intent.putExtra(IDoegelConstants.MESSAGE_ID_EXTRA, messageId);
				if (MessageDetailsActivity.this.getParent() == null) {
					MessageDetailsActivity.this.setResult(IDoegelConstants.MESSAGE_DELETED_RESULT, intent);
				} else {
					MessageDetailsActivity.this.getParent().setResult(IDoegelConstants.MESSAGE_DELETED_RESULT, intent);
				}
				finish();
			} else {
				dialog.dismiss();
				Utils.showAlertDialog(MessageDetailsActivity.this, getString(R.string.message_removing_error_title), getString(R.string.message_removing_error));
			}
			
			super.onPostExecute(result);
		}
	}
	
	private class SetMessageReadTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			return ((DoegelApplication) getApplication()).getHttpConnector().setMessageAsRead(MessageDetailsActivity.this, message.id);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				try {
					unreadMessage = true;
					message.read = true;
					getHelper().getInboxDao().update((IncomingMessage)message);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
			super.onPostExecute(result);
		}
	}
	
	private static final int CONTEXT_MENU_HOME = 0;
	private static final int CONTEXT_MENU_COMPOSE = 1;
	private static final int CONTEXT_MENU_REPLY = 2;
	private static final int CONTEXT_MENU_FORWARD = 3;
	private static final int CONTEXT_MENU_DELETE = 4;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, CONTEXT_MENU_HOME, 0, R.string.home_context_menu);
		menu.add(0, CONTEXT_MENU_COMPOSE, 0, R.string.compose_message_context_menu);
		menu.add(0, CONTEXT_MENU_REPLY, 0, R.string.reply_message_context_menu);
		menu.add(0, CONTEXT_MENU_FORWARD, 0, R.string.forward_message_context_menu);
		menu.add(0, CONTEXT_MENU_DELETE, 0, R.string.delete_message_context_menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CONTEXT_MENU_HOME:
			startActivity(Utils.createHomeIntent(this));
			return true;
		case CONTEXT_MENU_COMPOSE:
			composeMessage();
			return true;
		case CONTEXT_MENU_REPLY:
			replyMessage();
			return true;
		case CONTEXT_MENU_FORWARD:
			forwardMessage();
			return true;
		case CONTEXT_MENU_DELETE:
			deleteMessage();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
